package com.css.zfzx.sjcj.modules.qhseismicfortification.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.BeanUtil;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.entity.QhDrillOverviewEntity;
import com.css.zfzx.sjcj.modules.qhriskvisualshow.repository.entity.QhProbabilityEarthquakeDangerEntity;
import com.css.zfzx.sjcj.modules.qhseismicfortification.repository.QhSeismicFortificationNativeRepository;
import com.css.zfzx.sjcj.modules.qhseismicfortification.repository.QhSeismicFortificationRepository;
import com.css.zfzx.sjcj.modules.qhseismicfortification.repository.entity.QhSeismicFortificationEntity;
import com.css.zfzx.sjcj.modules.qhseismicfortification.service.QhSeismicFortificationService;
import com.css.zfzx.sjcj.modules.qhseismicfortification.viewobjects.QhSeismicFortificationQueryParams;
import com.css.zfzx.sjcj.modules.qhseismicfortification.viewobjects.QhSeismicFortificationVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author tao
 * @date 2020-11-17
 */
@Slf4j
@Service
public class QhSeismicFortificationServiceImpl implements QhSeismicFortificationService {

	@Autowired
    private QhSeismicFortificationRepository qhSeismicFortificationRepository;
    @Autowired
    private QhSeismicFortificationNativeRepository qhSeismicFortificationNativeRepository;

    @Override
    public JSONObject queryQhSeismicFortifications(QhSeismicFortificationQueryParams queryParams, int curPage, int pageSize) {
        Page<QhSeismicFortificationEntity> qhSeismicFortificationPage = this.qhSeismicFortificationNativeRepository.queryQhSeismicFortifications(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhSeismicFortificationPage);
        return jsonObject;
    }


    @Override
    public QhSeismicFortificationEntity getQhSeismicFortification(String id) {
        QhSeismicFortificationEntity qhSeismicFortification = this.qhSeismicFortificationRepository.findById(id).orElse(null);
         return qhSeismicFortification;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhSeismicFortificationEntity saveQhSeismicFortification(QhSeismicFortificationEntity qhSeismicFortification) {
        String uuid = UUIDGenerator.getUUID();
        qhSeismicFortification.setId(uuid);
        qhSeismicFortification.setCreateUser(PlatformSessionUtils.getUserId());
        qhSeismicFortification.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhSeismicFortification.setIsValid("1");
        qhSeismicFortification.setReviewStatus("0");
        qhSeismicFortification.setQualityinspectionStatus("0");
        this.qhSeismicFortificationRepository.save(qhSeismicFortification);
        return qhSeismicFortification;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhSeismicFortificationEntity updateQhSeismicFortification(QhSeismicFortificationEntity qhSeismicFortification) {
        qhSeismicFortification.setUpdateUser(PlatformSessionUtils.getUserId());
        qhSeismicFortification.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = qhSeismicFortification.getId();
        QhSeismicFortificationEntity one = qhSeismicFortificationRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(qhSeismicFortification, one);
        this.qhSeismicFortificationRepository.save(one);
        return qhSeismicFortification;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhSeismicFortifications(List<String> ids) {
        List<QhSeismicFortificationEntity> qhSeismicFortificationList = this.qhSeismicFortificationRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhSeismicFortificationList) && qhSeismicFortificationList.size() > 0) {
            for(QhSeismicFortificationEntity qhSeismicFortification : qhSeismicFortificationList) {
//                this.qhSeismicFortificationRepository.delete(qhSeismicFortification);
                qhSeismicFortification.setUpdateUser(PlatformSessionUtils.getUserId());
                qhSeismicFortification.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhSeismicFortification.setIsValid("0");
                this.qhSeismicFortificationRepository.save(qhSeismicFortification);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhSeismicFortification(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhSeismicFortificationEntity> qhSeismicFortificationList = this.qhSeismicFortificationRepository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhSeismicFortificationList) && qhSeismicFortificationList.size() > 0) {
            for(QhSeismicFortificationEntity qhSeismicFortification : qhSeismicFortificationList) {
                qhSeismicFortification.setUpdateUser(PlatformSessionUtils.getUserId());
                qhSeismicFortification.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhSeismicFortification.setReviewStatus("1");
                this.qhSeismicFortificationRepository.save(qhSeismicFortification);
            }
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            params.setTitleRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<QhSeismicFortificationVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), QhSeismicFortificationVO.class, params);
            List<QhSeismicFortificationVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<QhSeismicFortificationVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    QhSeismicFortificationVO areaVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + areaVO.getRowNum() + "行" + areaVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public String exportExcel(String ids, HttpServletResponse response) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhSeismicFortificationEntity> areaEntities = this.qhSeismicFortificationRepository.findAllById(idList);

        return exportExcel(areaEntities,response);
    }

    @Override
    public String exportExcel(List<QhSeismicFortificationEntity> areaEntities, HttpServletResponse response) {
        try {
            // 深拷贝
            ArrayList<QhSeismicFortificationVO> vos = new ArrayList<>();
            for (QhSeismicFortificationEntity areaEntity : areaEntities) {
                QhSeismicFortificationVO vo = new QhSeismicFortificationVO();
                BeanUtils.copyProperties(areaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "抗震设防参数统计", "抗震设防参数", QhSeismicFortificationVO.class, "抗震设防参数.xls", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private void saveExcel(List<QhSeismicFortificationVO> list) {
        for (int i = 0; i < list.size(); i++) {
//            QhSeismicFortificationEntity areaEntity = new QhSeismicFortificationEntity();
            QhSeismicFortificationVO areaVO = list.get(i);
            QhSeismicFortificationEntity areaEntity = qhSeismicFortificationRepository.findById(areaVO.getId()).get();
            // 将VO数据映射拷贝到库表中
            BeanUtil.copyPropertiesIgnoreNull(areaVO, areaEntity);
            updateQhSeismicFortification(areaEntity);
        }
    }

    private void setCheckFields(Map<String,String> fields){
        fields.put("projectName","勘察工程名称");
        fields.put("drillCode","钻孔编号");
        fields.put("serialNumber","序号");
        fields.put("geotechnicalType","岩土类型");
        fields.put("standardStartDepth","标准贯入起始深度");
        fields.put("standardEndDepth","标准贯入结束深度");
        fields.put("standardHammerNumber","标准贯入锤击数");
        fields.put("standardMeasuredValue","标准贯入实验实测值");
        fields.put("province","省");
        fields.put("city","市");
        fields.put("area","区/县");
    }

    @Override
    public JSONObject dataQualityCheck(List<QhSeismicFortificationEntity> qhStandardPenetrationList){
        JSONObject res = new JSONObject();

        try {
            if(PlatformObjectUtils.isEmpty(qhStandardPenetrationList) || qhStandardPenetrationList.size() < 1) {
                return res;
            }

            Map<String, QhDrillOverviewEntity> drillCodeEntityMap = new HashMap<>();

            for(QhSeismicFortificationEntity qhStandardPenetration : qhStandardPenetrationList){
                //检查字段值不为空
                StringBuilder errorMsg = new StringBuilder();
                Map<String, String> methods = new HashMap<>();
                setCheckFields(methods);

                ServerUtil.checkFieldNull(qhStandardPenetration, methods, errorMsg);

                //写入系统质检原因
                String strErrorMsg = errorMsg.toString();
                if(!strErrorMsg.isEmpty()) {
                    qhStandardPenetration.setQualityinspectionComments(strErrorMsg);
                    qhStandardPenetration.setQualityinspectionStatus("1");
                    qhStandardPenetration.setQualityinspectionResult("0");
                    this.updateQhSeismicFortification(qhStandardPenetration);

                    res.put(qhStandardPenetration.getId(),strErrorMsg);
                } else {
                    qhStandardPenetration.setQualityinspectionStatus("1");
                    qhStandardPenetration.setQualityinspectionResult("1");
                    this.updateQhSeismicFortification(qhStandardPenetration);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return res;
    }

    @Override
    public JSONObject dataQualityCheck(String drillCodes){
        List<String> idList = Arrays.asList(drillCodes.split(","));
        List<QhSeismicFortificationEntity> qhStandardPenetrationList = this.qhSeismicFortificationRepository.findByIsValidAndDrillCodeIn("1",idList);

        return dataQualityCheck(qhStandardPenetrationList);
    }
}
